import React, {Component} from 'react'
//import axios from "axios"
import PubSub from 'pubsub-js'
import queueName from "../../common";

class Search extends Component {
    search = async () => {
        //获取输入(连续结构赋值+重命名)
        let {keyword: {value: val}} = this;
        //通知list更新状态
        PubSub.publish(queueName, {isFirst: false, isLoading: true})
        //发送网络请求
        // axios.get(`https://api.github.com/search/users?q=${val}`).then(
        //     value => {
        //         //通知list更新状态，展示数据
        //         PubSub.publish(queueName, {isLoading: false, users: value.data.items})
        //     },
        //     error => {
        //         //通知list更新状态显示错误
        //         PubSub.publish(queueName, {isLoading: false, err: error.message})
        //     }
        // )
        //使用fetch发送请求(未优化)
        // fetch(`https://api.github.com/search/users?q=${val}`).then(
        //     success => {
        //         console.log('联系服务器成功了')
        //         return success.json();
        //     },
        //     // error => {
        //     //     console.log('联系服务器失败了')
        //     //     return new Promise(() => {})
        //     // }
        // ).then(
        //     success => {
        //         console.log('获取数据成功了',success)
        //     },
        //     error => {
        //         console.log('获取数据失败了',error)
        //     }
        // )
        //使用fetch发送请求(优化)
        try {
            let response = await fetch(`https://api.github.com/search/users?q=${val}`)
            let result = await response.json()
            console.log(result)
            PubSub.publish(queueName, {isLoading: false, users: result.items})
        }catch (error) {
            PubSub.publish(queueName, {isLoading: false, err: error.message})
        }

    }

    render() {
        return (
            <section className="jumbotron">
                <h3 className="jumbotron-heading">搜索用户</h3>
                <div>
                    <input ref={c => this.keyword = c} type="text" placeholder="输入关键词搜索"/>&nbsp;
                    <button onClick={this.search}>搜索用户</button>
                </div>
            </section>
        );
    }
}

export default Search;